<template>
  <div>
    <div v-for="(item, index) in list" :key="index" class="video-item">
      <div :title="item.name" @click="handlePlay(item.url)">{{ item.name }}</div>
      <i class="el-icon-close" @click="handleDelete(index)" />
    </div>
    <el-upload :action="action" :before-upload="handleBeforeUpload" :on-success="handleUploadSuccess"
      :on-error="handleUploadError" name="file" :show-file-list="false" :headers="headers"
      accept=".mp4,.m3u8,.flv,.avi,.mkv,.mov,.wmv,.rmvb,.ts,.3gp,.f4v,.webm">
      <el-button size="small" type="primary">上传视频</el-button>
    </el-upload>
  </div>
</template>
<script>
import { getToken } from "@/utils/auth";
import { updateDevice, updateDeviceVideo, deleteDeviceVideo } from "@/api/device/system.js";
export default {
  name: "Device",
  data() {
    return {
      action: process.env.VUE_APP_BASE_API + "/common/upload", // 上传的图片服务器地址
      headers: {
        Authorization: "Bearer " + getToken(),
      },
      fileType: ["mp4", "m3u8", "flv"],
      fileSize: 1024, // 大小限制(MB)
    };
  },
  props: {
    urls: {
      type: String,
      default: "",
      required: true,
    },
    systemId: {
      type: [String, Number],
      default: "",
    },
    deviceId: {
      type: [String, Number],
      default: "",
    },
  },
  computed: {
    list() {
      let arr = this.urls?.split(",") || [];
      arr = arr
        .filter((i) => i)
        .map((i) => {
          return {
            // name: i.split("/").pop(),
            name: i.split("/").pop().split("_")[0] + '.' + i.split("/").pop().split(".")[1],
            url: i,
          };
        });
      return arr;
    },
  },
  methods: {
    // 上传前验证
    handleBeforeUpload(file) {
      let isImg = false;
      if (this.fileType.length) {
        let fileExtension = "";
        if (file.name.lastIndexOf(".") > -1) {
          fileExtension = file.name.slice(file.name.lastIndexOf(".") + 1);
        }
        isImg = this.fileType.some((type) => {
          if (file.type.indexOf(type) > -1) return true;
          if (fileExtension && fileExtension.indexOf(type) > -1) return true;
          return false;
        });
      } else {
        isImg = file.type.indexOf("video") > -1;
      }

      if (!isImg) {
        this.$modal.msgError(
          `文件格式不正确, 请上传${this.fileType.join("/")}视频格式文件!`
        );
        return false;
      }
      if (this.fileSize) {
        const isLt = file.size / 1024 / 1024 < this.fileSize;
        if (!isLt) {
          this.$modal.msgError(`上传视频大小不能超过 ${this.fileSize} MB!`);
          return false;
        }
      }
      this.$modal.loading("正在上传视频，请稍候...");
    },
    // 上传失败
    handleUploadError(err) {
      this.$modal.msgError("上传文件失败，请重试");
      this.$modal.closeLoading();
    },
    // 上传成功回调
    handleUploadSuccess(res, file) {
      this.$modal.closeLoading();
      if (res.code === 200) {
        this.list.push({
          name: res.fileName.split("/").pop(),
          url: res.fileName,
        });
        // this.handleEditVideo();
        this.addHandleEditVideo()
      }
    },
    // 删除视频
    handleDelete(index) {
      this.$confirm("是否确认删除该视频?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        this.list.splice(index, 1);
        // this.handleEditVideo();
        this.addHandleEditVideo()
      });
    },
    // 播放视频
    handlePlay(url) {
      window.open(process.env.VUE_APP_BASE_API + url, "_blank");
    },

    // 新增视频
    addHandleEditVideo() {
      // updateDevice({
      //   referenceVideo: this.list.map((item) => item.url).join(","),
      //   id: this.deviceId,
      //   systemId: this.systemId,
      // }).then((res) => {
      //   this.$emit("uploadSuccess");
      // });
      updateDeviceVideo({
        referenceVideo: this.list.map((item) => item.url).join(","),
        referenceVideoName: this.list.map((item) => item.name).join(","),
        id: this.deviceId,
        systemId: this.systemId,
      }).then((res) => {
        this.$emit("uploadSuccess");
      });
    },
    // 更新视频
    handleEditVideo() {
      updateDevice({
        referenceVideo: this.list.map((item) => item.url).join(","),
        id: this.deviceId,
        systemId: this.systemId,
      }).then((res) => {
        this.$emit("uploadSuccess");
      });

    },



    // 新增视频
    addHandleEditVideo() {
      // updateDevice({
      //   referenceVideo: this.list.map((item) => item.url).join(","),
      //   id: this.deviceId,
      //   systemId: this.systemId,
      // }).then((res) => {
      //   this.$emit("uploadSuccess");
      // });
      updateDeviceVideo({
        referenceVideo: this.list.map((item) => item.url).join(","),
        referenceVideoName: this.list.map((item) => item.name).join(","),
        id: this.deviceId,
        systemId: this.systemId,
      }).then((res) => {
        this.$emit("uploadSuccess");
      });
    },
    // 更新视频
    handleEditVideo() {
      updateDevice({
        referenceVideo: this.list.map((item) => item.url).join(","),
        id: this.deviceId,
        systemId: this.systemId,
      }).then((res) => {
        this.$emit("uploadSuccess");
      });

    },
  },
};
</script>
<style lang="scss" scoped>
.video-item {
  padding: 2px 10px;
  border: 1px solid #ccc;
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 4px;

  &:hover {
    cursor: pointer;
  }

  div {
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
}
</style>
